package com.huilink.webmail.service.api;

import java.util.Map;

import javax.persistence.EntityManagerFactory;

public abstract class WebMailServiceFactory {
	public static final String KEY_IMPLEMENTATION_CLASS = "WebMailService.Implementation";
	public static final String VAL_WEBMAILSERVICE_MGR          = "com.huilink.webmail.service.impl.WebMailServiceFactoryImpl";	
	
	protected EntityManagerFactory entityManagerFactory;
	
	public static WebMailServiceFactory createFactory(Map<String, Object> map) {
		String className = VAL_WEBMAILSERVICE_MGR;
		if(map != null) {
			Object tmp = map.get(KEY_IMPLEMENTATION_CLASS);
			if(!(tmp instanceof String))
				throw new IllegalArgumentException("key=MediaFactory.KEY_IMPLEMENTATION_CLASS must be of type String and wasn't");
			if(tmp != null)
				className = (String)tmp;
		}

		WebMailServiceFactory retVal = null;
		try {
			Class<? extends WebMailServiceFactory> theClass = Class.forName(className).asSubclass(WebMailServiceFactory.class);
			retVal = theClass.newInstance();
			retVal.configure(map);
//			Class theClass = Class.forName(className);
//			retVal = (ChannelManagerFactory)theClass.newInstance();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("Class not found.  See the exception causing this one for more info.", e);
		} catch (InstantiationException e) {
			throw new RuntimeException("bug", e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("bug", e);
		}
		
		return retVal; 
	}

	public void setEntityManagerFactory(EntityManagerFactory entityManager) {
		this.entityManagerFactory = entityManager;
	}
	
	protected abstract void configure(Map<String, Object> map);

	public abstract WebMailService createWebMailService();
	
	
}
